package org.jeecg.modules.order.controller;

import java.math.BigDecimal;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.request.WxPayRefundV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.weaver.ast.Or;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.controller.JeecgController;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.service.IMyCouponService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.order.service.IOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.entity.OrderRecharge;
import org.jeecg.modules.recharge.service.IBalanceService;
import org.jeecg.modules.recharge.service.IOrderRechargeService;
import org.jeecg.modules.system.util.DateUtil;
import org.jeecg.modules.system.util.MenJinUtil;
import org.jeecg.modules.voucher.entity.Voucher;
import org.jeecg.modules.voucher.service.IVoucherService;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecg.modules.zixishi.service.IQuyuService;
import org.jeecg.modules.zixishi.service.ISeatService;
import org.jeecg.modules.zixishi.service.IZixishiService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date:   2024-05-19
 * @Version: V1.0
 */
@Api(tags="订单")
@RestController
@RequestMapping("/order/order")
@Slf4j
public class OrderController extends JeecgController<Order, IOrderService> {
	@Autowired
	private IOrderService orderService;

	@Autowired
	private IZixishiService zixishiService;
	@Autowired
	private ISeatService seatService;
	@Autowired
	private IQuyuService quyuService;
	@Autowired
	private RedisUtil redisUtil;

	 @Autowired
	 private IBalanceService balanceService;

	 @Autowired
	 private IMyCouponService myCouponService;
	 @Autowired
	 private IVoucherService voucherService;
	/**
	 * 分页列表查询
	 *
	 * @param order
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "订单-分页列表查询")
	@ApiOperation(value="订单-分页列表查询", notes="订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Order>> queryPageList(Order order,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Order> queryWrapper = QueryGenerator.initQueryWrapper(order, req.getParameterMap());
		Page<Order> page = new Page<Order>(pageNo, pageSize);
		IPage<Order> pageList = orderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param order
	 * @return
	 */
	@AutoLog(value = "订单-添加")
	@ApiOperation(value="订单-添加", notes="订单-添加")
	//@RequiresPermissions("org.jeecg.modules:sr_order:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Order order) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try{
			Result<String> result = orderService.addOrder(sysUser,order);
			return result;
		}catch (Exception e){
			return Result.error(e.getMessage());
		}
	}

	 @SneakyThrows
     @AutoLog(value = "订单-添加")
	 @ApiOperation(value="订单-添加", notes="订单-添加")
	 //@RequiresPermissions("org.jeecg.modules:sr_order:add")
	 @PostMapping(value = "/doOrder")
	 public Result<Order> doOrder(@RequestBody Order order) {

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String voucherId = order.getVoucherId();
		 Voucher voucher = null;
		 if(StringUtils.isNotBlank(voucherId)){
			 voucher = voucherService.getById(voucherId);
			 if(voucher == null || voucher.getUseStatus() == 1 || voucher.getEffectEndTime().getTime()< new Date().getTime() || voucher.getEffectStartTime().getTime()> new Date().getTime() ){
				return Result.error("优惠券不可用，请核实");
			 }
		 }
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 Map priceMap = seatService.seatPrice(order.getQuyuId(),order.getReserveType(),format.format(order.getStartTime()),format.format(order.getEndTime()));
		 Float orderMoney = Float.valueOf("" + priceMap.get("total"));
		 if(null != voucher){
			orderMoney = orderMoney - voucher.getAmt().floatValue();
		 }
		 orderMoney = orderMoney>0?orderMoney:0;
		 if(orderMoney-Float.valueOf(order.getOrderMoney()) != 0){
			return Result.error("订单金额计算有误，请重试");
		 }
		 orderService.doOrder(sysUser,order,voucher);

		 return Result.OK(order);
	 }

	 @SneakyThrows
	 @AutoLog(value = "卡券预约订单-添加")
	 @ApiOperation(value="卡券预约订单-添加", notes="卡券预约订单-添加")
	 //@RequiresPermissions("org.jeecg.modules:sr_order:add")
	 @PostMapping(value = "/doOrder4Coupon")
	 public Result<Order> doOrder4Coupon(@RequestBody Order order) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 MyCoupon myCoupon = myCouponService.getById(order.getMyCouponId());
		 if(null == myCoupon){
			 return Result.error("卡券信息不存在，请核实");
		 }

		 Date st = myCoupon.getEffectStartDate();
		 Date et = myCoupon.getEffectEndDate();
		if(st.getTime()>new Date().getTime() || et.getTime()<new Date().getTime()){
			return Result.error("不在卡券有效期内，请核实");
		}
		if(myCoupon.getUseStatus() == 1 && !(myCoupon.getDurationLeft()>0)){
			return Result.error("卡券已使用，请到预约订单中查看");
		}
		if(!StringUtils.equals(sysUser.getId(),myCoupon.getSysUserId())){
			return Result.error("请使用本人卡券预约");
		}
		double durationLeft = 0;
		if(myCoupon.getCouponType() == 1) {
			if (cn.hutool.core.date.DateUtil.betweenDay(order.getStartTime(), order.getEndTime(),false)!=0) {
				return Result.error("小时订单开始和结束日期需要在同一天");
			}

			Zixishi zixishi = zixishiService.getById(order.getZixishiId());
			Date s = StringUtils.isBlank(myCoupon.getUseStartTime())? new SimpleDateFormat("HH:mm:ss").parse(zixishi.getStarttime()): new SimpleDateFormat("HH:mm:ss").parse(myCoupon.getUseStartTime());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(s);
			calendar.add(Calendar.MINUTE,-1);
			s = calendar.getTime();
			Date e = StringUtils.isBlank(myCoupon.getUseEndTime())? new SimpleDateFormat("HH:mm:ss").parse(zixishi.getEndtime()): new SimpleDateFormat("HH:mm:ss").parse(myCoupon.getUseEndTime());
			if(e.before(s)){
				e = org.apache.commons.lang3.time.DateUtils.addDays(e,1);
			}
			calendar.setTime(e);
			calendar.add(Calendar.MINUTE,1);
			e = calendar.getTime();
			if(order.getStartTime().compareTo(order.getEndTime())>=0){
				return Result.error("请确认预约时长");
			}
			Date viss = new SimpleDateFormat("HH:mm:ss").parse(cn.hutool.core.date.DateUtil.format(order.getStartTime(),"HH:mm:ss"));
			Date vise = new SimpleDateFormat("HH:mm:ss").parse(cn.hutool.core.date.DateUtil.format(order.getEndTime(),"HH:mm:ss"));
			if(vise.before(viss)){
				vise = DateUtils.addDays(vise,1);
			}
			if (viss.before(s) || vise.after(e)) {
				return Result.error("使用时间为:" + (StringUtils.isNotBlank(myCoupon.getUseStartTime())?myCoupon.getUseStartTime(): zixishi.getStarttime()) + "--" +
						(StringUtils.isNotBlank(myCoupon.getUseEndTime())?myCoupon.getUseEndTime():zixishi.getEndtime()) + " 请重新选择时间");
			}
			long t = cn.hutool.core.date.DateUtil.between(order.getStartTime(),order.getEndTime(), DateUnit.MINUTE);
			float tt = t%30>0?(t/60f)+0.5f:t/60f;
			durationLeft = (double) (myCoupon.getDurationLeft().floatValue() - tt);
		}else{
			//天
			long d = cn.hutool.core.date.DateUtil.between(order.getStartTime(),order.getEndTime(), DateUnit.DAY)+1;
			durationLeft = (double) (myCoupon.getDurationLeft().floatValue() - d);
		}
		myCoupon.setDurationLeft(durationLeft);
		orderService.doOrder4Coupon(sysUser,order,myCoupon);

		 return Result.OK(order);
	 }
	/**
	 *  编辑
	 *
	 * @param order
	 * @return
	 */
	@AutoLog(value = "订单-编辑")
	@ApiOperation(value="订单-编辑", notes="订单-编辑")
	//@RequiresPermissions("org.jeecg.modules:sr_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Order order) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            Result<String> result = orderService.editOrder(sysUser,order);
			return result;
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单-通过id删除")
	@ApiOperation(value="订单-通过id删除", notes="订单-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:sr_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		Order order = orderService.getById(id);
		if(null == order){
			return Result.error("订单不存在");
		}
		String status = order.getOrderStatus();
		if(!(StringUtils.equals("1",status) || StringUtils.equals("2",status))){
			orderService.removeById(id);
			return Result.OK("删除成功!");
		}else {
			return Result.error("订单状态不允许删除!");
		}
	}

	 @AutoLog(value = "订单-通过id删除自己订单")
	 @ApiOperation(value="订单-通过id删除自己订单", notes="订单-通过id删除自己订单")
	 //@RequiresPermissions("org.jeecg.modules:sr_order:delete")
	 @GetMapping(value = "/deleteMyOrder")
	 public Result<String> deleteMyOrder(@RequestParam(name="id",required=true) String id) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Order order = orderService.getById(id);
		 if(null == order || !StringUtils.equals(sysUser.getId(),order.getSysUserId())){
			 return Result.error("订单不存在");
		 }
		 String status = order.getOrderStatus();
		 if(!(StringUtils.equals("1",status) || StringUtils.equals("2",status))){
			 orderService.removeById(id);
			 return Result.OK("删除成功!");
		 }else {
			 return Result.error("订单状态不允许删除!");
		 }
	 }
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "订单-批量删除")
	@ApiOperation(value="订单-批量删除", notes="订单-批量删除")
	//@RequiresPermissions("org.jeecg.modules:sr_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.orderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "订单-通过id查询")
	@ApiOperation(value="订单-通过id查询", notes="订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Order> queryById(@RequestParam(name="id",required=true) String id) {
		Order order = orderService.getById(id);
		if(order==null) {
			return Result.error("未找到对应数据");
		}
		long exp = redisUtil.getExpire("orderseat:quxiao:" + order.getOrderNum());
		order.setPayLeft(exp);
		return Result.OK(order);
	}

	 @ApiOperation(value="订单-通过num查询", notes="订单-通过num查询")
	 @GetMapping(value = "/queryByOrderNum")
	 public Result<Order> queryByOrderNum(@RequestParam(name="orderNum",required=true) String orderNum) {
		 Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum, orderNum));
		 if(order==null) {
			 return Result.error("未找到对应数据");
		 }
		 long exp = redisUtil.getExpire("orderseat:quxiao:" + order.getOrderNum());
		 order.setPayLeft(exp);
		 return Result.OK(order);
	 }

	 @ApiOperation(value="获取最近的订单", notes="获取最近的订单")
	 @GetMapping(value = "/nearlyorder")
	 public Result<Order> nearlyOrder() {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		queryWrapper.eq(Order::getSysUserId, sysUser.getId())
				.in(Order::getOrderStatus, "1","2")
				.orderByDesc(Order::getOrderStatus)
				.orderByAsc(Order::getStartTime)
				.last("limit 1");

		 Order order = orderService.getOne(queryWrapper);

		 return Result.OK(order);
	 }

	 @ApiOperation(value="小程序展示的订单列表", notes="小程序展示的订单列表")
	 @GetMapping(value = "/myorder")
	 public Result<IPage<Order>> myOrder(@RequestParam(required = false) List<String> status,@RequestParam(required = false) String keyWord) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		 QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
//		 queryWrapper.eq("sys_user_id", sysUser.getId())
//				 .in("order_status",status)
//				 .orderByAsc("field(order_status,'2','0','1','5','4','3')")
//				 .orderByDesc("update_time");

		 MPJLambdaWrapper<Order> queryWrapper = new MPJLambdaWrapper<Order>()
				 .selectAll(Order.class)
				 .selectAs(Zixishi::getLogo,"zixishiLogo")
				 .selectAs(Quyu::getLogo,"quyuLogo")
				 .leftJoin(Zixishi.class, Zixishi::getId, Order::getZixishiId)
				 .leftJoin(Quyu.class, Quyu::getId, Order::getQuyuId)
				 .leftJoin(Seat.class, Seat::getId, Order::getSeatId)
				 .eq(Order::getSysUserId,sysUser.getId())
				 .in(CollectionUtil.isNotEmpty(status), Order::getOrderStatus,status)
				 .and(StringUtils.isNotBlank(keyWord),
						 wp->wp.like(Zixishi::getName,keyWord)
								 .or().like(Quyu::getName,keyWord)
								 .or().like(Seat::getName,StringUtils.upperCase(keyWord))
								 .or().like(Order::getUname,keyWord)
								 .or().like(Order::getUphone,keyWord)
				 )
		 		 .orderByAsc("field(order_status,'2','0','1','5','4','3')")
				 .orderByDesc("update_time");

		 Page<Order> page = new Page<Order>(0, 199);
		 IPage<Order> pageList = orderService.page(page, queryWrapper);
//		 List<Zixishi> zixishiList = zixishiService.list();
//		 Map<String,Zixishi> zixishiMap;
//		 if(zixishiList!=null && zixishiList.size()>0){
//			 zixishiMap = zixishiList.stream().collect(Collectors.toMap(Zixishi::getId, a -> a,(k1,k2)->k1));
//		 } else {
//             zixishiMap = new HashMap<String, Zixishi>();
//         }
//         pageList.getRecords().stream().forEach(order -> {
//			String zixishiId = order.getZixishiId();
//			Zixishi zixishi = zixishiMap.get(zixishiId);
//			if(zixishi!=null){
//				order.setZixishi(zixishi);
//			}
//		 });
		 return Result.OK(pageList);

	 }

	 @ApiOperation(value="订单-通过id查询", notes="订单-通过id查询")
	 @GetMapping(value = "/orderdetail")
	 public Result<IPage<Order>> orderDetail(@RequestParam(name="id",required=true) String id) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		 queryWrapper.eq(Order::getSysUserId, sysUser.getId())
				 .eq(Order::getId,id);

		 Page<Order> page = new Page<Order>(1, 1);
		 IPage<Order> pageList = orderService.page(page, queryWrapper);

		 pageList.getRecords().stream().forEach(order -> {
			 String zixishiId = order.getZixishiId();
			 Zixishi zixishi = zixishiService.getById(zixishiId);
			 if(zixishi!=null){
				 order.setZixishi(zixishi);
			 }
			 String quyuId = order.getQuyuId();
			 Quyu quyu = quyuService.getById(quyuId);
			 if(quyu!=null){
				 order.setQuyu(quyu);
			 }
		 });
		 return Result.OK(pageList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param order
    */
    //@RequiresPermissions("org.jeecg.modules:sr_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Order order) {
		String exportFields = this.getExportFields(Order.class,"seatorder:");
        return super.exportXls(request, order, Order.class, "预约订单",exportFields);
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("sr_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Order.class);
    }


	 @AutoLog(value = "订单-管理员操作退款")
	@ApiOperation(value = "管理员操作退款")
	 @RequestMapping(value = "/backMoney", method = RequestMethod.POST)
	 public Result<?> backMoney(@RequestBody Map backOrder) {
		String orderId = "" + backOrder.get("orderId");
		Float backMoney = Float.valueOf("" + backOrder.get("money"));
		Order order = orderService.getById(orderId);
		if(order==null) {
			return Result.error("订单不存在");
		}
		if(backMoney> Float.valueOf(order.getOrderMoney())){
			return Result.error("退款金额大于订单金额，请核实");
		}
		if(!StringUtils.containsAny(order.getOrderStatus(),"1","2","3")){
			return Result.error("请核实订单状态，只有已付款未退款的订单可以发起退款");
		}
		if (backMoney > 0) {
			order.setBackMoney(String.valueOf(backMoney));
			order.setOrderStatus("5");
			if(StringUtils.equals(order.getPayType(),"0")) { //微信
				orderService.back4WxPay(order,backMoney);
			}else if (StringUtils.equals(order.getPayType(),"1")) { //余额
				orderService.back4Balance(order,backMoney);
			}else if(StringUtils.equals(order.getPayType(),"2")){ // 卡券
				return Result.error("卡券支付的订单无法退款");
			}else if(StringUtils.equals(order.getPayType(),"3")){ //优惠券
				return Result.error("优惠券订单无法退款");
			}
		}
		return Result.OK(order);
	 }

	 @ApiOperation(value="订单时间内未被占用的座位", notes="订单时间内未被占用的座位")
	 @GetMapping(value = "/seatlist")
	 public Result<Collection<Seat>> seatList(@RequestParam String orderId) {
		Order order = orderService.getById(orderId);
		if(!StringUtils.equals(order.getOrderStatus(),"2")){
			return Result.error("不是进行中的订单不允许换座");
		}
		Date startTime = order.getStartTime();
		Date endTime = order.getEndTime();
		String quyuId = order.getQuyuId();
		List<Seat> seatList = seatService.list(new LambdaQueryWrapper<Seat>().eq(Seat::getQuyuId,quyuId).eq(Seat::getStatus,"1"));
		Map<String,Seat> seatMap = seatList.stream().collect(Collectors.toMap(Seat::getId, a -> a,(k1,k2)->k1));
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		queryWrapper
				.in(Order::getOrderStatus,"0","1","2")
				.eq(Order::getQuyuId,quyuId)
				.lt(Order::getStartTime,endTime)
				.gt(Order::getEndTime,startTime);
		List<Order> orderList = orderService.list(queryWrapper);
		if(CollectionUtil.isNotEmpty(orderList)){
			for(Order o : orderList){
				seatMap.remove(o.getSeatId());
			}
		}
		 return Result.OK(seatMap.values());
//		 return Result.OK(order);
	 }

	 @ApiOperation(value="换座", notes="换座")
	 @GetMapping(value = "/changeseat")
	 public Result<String> changeSeat(@RequestParam String orderId, @RequestParam String seatId) {
		 Order order = orderService.getById(orderId);
		 if(!StringUtils.equals(order.getOrderStatus(),"2")){
			 return Result.error("不是进行中的订单不允许换座");
		 }
		 Date startTime = order.getStartTime();
		 Date endTime = order.getEndTime();
		 Seat seat = seatService.getById(seatId);
		 if(!StringUtils.equals(seat.getStatus(),"1")){
			 return Result.error("座位已经被锁定,请重新选择");
		 }
		 LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		 queryWrapper
				 .in(Order::getOrderStatus,"0","1","2")
				 .eq(Order::getSeatId,seatId)
				 .lt(Order::getStartTime,endTime)
				 .gt(Order::getEndTime,startTime);
		 List<Order> orderList = orderService.list(queryWrapper);
		 if(CollectionUtil.isNotEmpty(orderList)){
			 return Result.error("座位被占用,请重新选择");
		 }
		 order.setSeatId(seatId);
		 orderService.updateById(order);
		 return Result.OK("操作成功");
	 }

	 @ApiOperation(value="加时费", notes="加时费")
	 @GetMapping(value = "/timemoney")
	 public Result<String> timeMoney(@RequestParam String orderId, @RequestParam Integer hours) {
		 Order order = orderService.getById(orderId);
		 if(!StringUtils.equals(order.getOrderStatus(),"2")){
			 return Result.error("不是进行中的订单不允许加时");
		 }
		 String seatId = order.getSeatId();
		 Date startTime = order.getEndTime();
		 Date endTime = order.getEndTime();
		 Calendar calendar = Calendar.getInstance();
		 calendar.setTime(endTime);
		 calendar.add(Calendar.HOUR_OF_DAY, hours);
		 endTime = calendar.getTime();
		 Seat seat = seatService.getById(seatId);
		 if(!StringUtils.equals(seat.getStatus(),"1")){
			 return Result.error("座位已经被锁定,不允许加时");
		 }
		 LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		 queryWrapper
				 .in(Order::getOrderStatus,"0","1","2")
				 .eq(Order::getSeatId,seatId)
				 .lt(Order::getStartTime,endTime)
				 .gt(Order::getEndTime,startTime);
		 List<Order> orderList = orderService.list(queryWrapper);
		 if(CollectionUtil.isNotEmpty(orderList)){
			 return Result.error("座位被占用,不允许加时");
		 }
		 Quyu quyu = quyuService.getById(order.getQuyuId());
		 if(!StringUtils.equals("" + quyu.getStatus(),"1")){
			 return Result.error("该区域不允许加时");
		 }
		 String price = quyu.getTimePrice();
		 Float p = Float.valueOf(price)*hours;

		 return Result.OK("" + p);
	 }

	 @ApiOperation(value="订单取消原因", notes="订单取消原因")
	 @GetMapping(value = "/cancelReason")
	 public Result<String> cancelReason(@RequestParam String orderId, @RequestParam(required = false) String remark) {
		 Order order = orderService.getById(orderId);
		 if(null != order){
			 String m = order.getRemark();
			 if(StringUtils.isNotBlank(m)){
				 remark = remark + " " + m;
 			 }
			order.setRemark(remark);
			orderService.updateById(order);
		 }
		 return Result.OK("操作成功");
	 }

	 @ApiOperation(value="取消订单", notes="取消订单")
	 @GetMapping(value = "/cancelorder")
	 public Result<String> cancelOrder(@RequestParam String orderId) {
		 Order order = orderService.getById(orderId);

		 if(StringUtils.equals(order.getOrderStatus(),"1") || StringUtils.equals(order.getOrderStatus(),"0")) {

			 Quyu quyu = quyuService.getById(order.getQuyuId());

			 Date startTime = order.getStartTime();
			 Date now = new Date();
			 int hours = DateUtil.hoursDiff(now, startTime);
			 int days = DateUtil.daysDiff(now, startTime);
			 Float money = Float.valueOf(order.getOrderMoney());
			 Float backMoney = 0f;
			 if(StringUtils.equals("datetime",order.getReserveType())){
				 if (hours > 1) {
					 backMoney = money;
				 } else {
					 backMoney = money - Float.valueOf(quyu.getTimePrice());
				 }
			 }else{
				 if (days > 1) {
					 backMoney = money;
				 } else {
					 backMoney = money - Float.valueOf(quyu.getDayPrice());
				 }
			 }

			 if (StringUtils.equals(order.getOrderStatus(), "1") && backMoney > 0) {
				 order.setBackMoney(String.valueOf(backMoney));
				 order.setOrderStatus("5");
				 if(StringUtils.equals(order.getPayType(),"0")) { //微信
					orderService.back4WxPay(order,backMoney);
				 }else if (StringUtils.equals(order.getPayType(),"1")) { //余额
					 orderService.back4Balance(order,backMoney);
				 }else if(StringUtils.equals(order.getPayType(),"2")){ // 卡券
					 orderService.back4Coupon(order,backMoney,hours,days);
				 }else if(StringUtils.equals(order.getPayType(),"3")){ //优惠券

				 }
			 } else {
				 order.setOrderStatus("4");
				 orderService.updateById(order);
			 }

			 redisUtil.del("orderseat:start:" + order.getOrderNum(),"orderseat:quxiao:" + order.getOrderNum(),"orderseat:xudan:" + order.getOrderNum(),"orderseat:end:" + order.getOrderNum());

			 String voucherId = order.getVoucherId();
			 if(StringUtils.isNotBlank(voucherId)){
				 Voucher voucher = voucherService.getById(voucherId);
				 voucher.setUseStatus(0);
				 voucherService.updateById(voucher);
			 }
			 return Result.OK();
		 }else{
			 return Result.error("当前订单状态下不允许退款");
		 }
	 }

	 @ApiOperation(value="订单支付使用余额", notes="订单支付使用余额")
	 @PostMapping(value = "/payorder")
	 public Result<String> payOrder(@RequestBody Map paramMap) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String orderNum = "" + paramMap.get("orderNum");
		try {
			Result<String> result = orderService.payOrder(sysUser.getId(), orderNum);
			return result;
		}catch (Exception ex){
			return Result.error(ex.getMessage());
		}
	 }


}
